package com.fhc.location

import android.Manifest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.fhc.amap.AMapActivity
import com.fhc.amap.model.PositionItem
import com.tbruyelle.rxpermissions3.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        gaode.setOnClickListener{
            showAMap()
        }
    }

    private fun showAMap() {
        val rxPermissions = RxPermissions(this)
        val permissions: Array<String> = arrayOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE
        )

        rxPermissions.request(*permissions)
                .subscribe { aBoolean ->
                    when (aBoolean) {
                        true -> {
                            val intent = Intent(this, AMapActivity::class.java)
                            startActivityForResult(intent, AMapActivity.POSITION_REQUEST_CODE)
                        }
                        false -> {
                            Toast.makeText(this, "请开启权限", Toast.LENGTH_SHORT)
                        }
                    }
                }
    }

    //接收返回的数据
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AMapActivity.POSITION_REQUEST_CODE && resultCode == RESULT_OK) {
            val positionItem = data!!.getParcelableExtra<PositionItem>(AMapActivity.SURE_POSITION)
            tv_address.text = "位置信息：$positionItem"
        }
    }
}